package com.tianyu.inspection.controller;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tianyu.inspection.common.Constants;
import com.tianyu.inspection.common.enums.FileTypeEnum;
import com.tianyu.inspection.common.enums.RoState;
import com.tianyu.inspection.common.annotation.Permission;
import com.tianyu.inspection.common.component.AppConstants;
import com.tianyu.inspection.common.component.Validate;
import com.tianyu.inspection.entity.PileCard;
import com.tianyu.inspection.entity.User;
import com.tianyu.inspection.entity.model.OperateMo;
import com.tianyu.inspection.entity.model.QueryMo;
import com.tianyu.inspection.entity.vo.Ro;
import com.tianyu.inspection.entity.vo.ServiceRo;
import com.tianyu.inspection.service.api.IPileCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**********************************
 * @Author YSW
 * @Description 桩牌接口
 * @Date 2021/1/15 - 18:31
 **********************************/

@Slf4j
@RestController
@RequestMapping("/api/2.0/pileCard")
public class PileCardController {

    @Resource
    private IPileCardService pileCardService;

    @Resource
    private Validate validateModel;

    @Resource
    private ValueOperations<String, Object> valueOperations;

    @Resource
    private AppConstants appConstants;

    @PostMapping(value = "/load")
    @Permission(value = 1,tags = Constants.API_SUPER)
    public Ro<List<PileCard>> loadPileCard(@RequestParam("file") MultipartFile pipelineFile){
        Ro<List<PileCard>> ro = new Ro<>();
        return ro.setContent(pileCardService.loadPileCard(pipelineFile,0));
    }

    @PostMapping(value = "/upload")
    @Permission(value = 1,tags = Constants.API_SUPER)
    public Ro<Object> uploadPileCard(@RequestParam("file") MultipartFile pipelineFile,
                                     @RequestParam("projectId") Integer projectId,
                                     @RequestParam("pipelineId") Integer pipelineId,
                                     @RequestParam("pipelineStationId") Integer pipelineStationId){
        Ro<Object> ro = new Ro<>();
        if (validateModel.projectIdValidate(projectId)){
            return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[projectId],值不存在");
        }
        if (validateModel.pipelineIdValidate(pipelineId,projectId)){
            return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineId],值不存在");
        }
        if (validateModel.pipelineStationIdValidate(pipelineStationId,projectId)){
            return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineStationId],值不存在");
        }
        final ServiceRo serviceRo = pileCardService.uploadPileCard(pipelineFile, projectId,pipelineId,pipelineStationId);
        if (serviceRo.getResult()){
            ro.setResultEnum(RoState.SUCCESS);
        }else {
            ro.setResultEnum(RoState.FAIL).setMessage("存在重复系统桩号").setContent(serviceRo.getData());
        }
        return ro;
    }

    @GetMapping(value = "/list")
    @Permission(value = 4,tags = Constants.API_PATROL)
    public Ro<IPage<PileCard>> getPageList(HttpServletRequest request, @RequestHeader("u-projectId") Integer projectId,
                                           @RequestHeader("u-uid") Integer userId){
        QueryMo queryMo = QueryMo.getQueryMo(request);
        Ro<IPage<PileCard>> ro = new Ro<>();
        int roleId = (int) request.getAttribute("roleId");
        if (roleId > 1){
            User loginUser = (User) valueOperations.get(appConstants.redisUserKey + userId);
            if (Objects.nonNull(loginUser)){
                final String infrastructureTypeUse = loginUser.getInfrastructureTypeUse();
                final String pileCardTypeUse = loginUser.getPileCardTypeUse();
                try {
                    final Map<String, JSONArray> modelMap = new HashMap<>(1);
                    final JSONArray jsonArray = JSONArray.parseArray(pileCardTypeUse);
                    if (Objects.isNull(jsonArray) || jsonArray.size() == 0){
                        return ro.setResultEnum(RoState.FAIL).setMessage("类型未配置");
                    }else {
                        modelMap.put("pile_card_type_id", jsonArray);
                    }
                    queryMo.setInMap(modelMap);
                }catch (Exception e){
                    log.error(e.getMessage());
                }
            }
        }
        queryMo.build(PileCard.class,projectId);
        return ro.setContent(pileCardService.searchListPage(queryMo));
    }

    @GetMapping(value = "/{id}")
    @Permission(value = 4,tags = Constants.API_PATROL)
    public Ro<PileCard> getOne(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<PileCard> ro = new Ro<>();
        if (Objects.isNull(id)){
            return ro.setResultEnum(RoState.PARAMS_MISS_ERROR);
        }
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(PileCard.class,projectId);
        PileCard pileCard = pileCardService.selectOne(queryMo);
        if (Objects.isNull(pileCard)){
            ro.setMessage("未查询到数据");
        }else {
            ro.setContent(pileCard);
        }
        return ro;
    }

    @PostMapping(value = "/insert")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<PileCard> insert(@RequestBody OperateMo operateMo, @RequestHeader("u-projectId") Integer projectId){
        Ro<PileCard> ro = new Ro<>();
        operateMo.createBuild(PileCard.class,projectId);
        if (operateMo.getEntity().size()==0){
            return ro.setResultEnum(RoState.FAIL).setMessage("无操作参数传入,请传参后重试");
        }
        String systemStakeNumber = (String) operateMo.getEntity().get("systemStakeNumber");
        String sceneImage = (String) operateMo.getEntity().get("sceneImage");
        Integer pileCardTypeId = (Integer) operateMo.getEntity().get("pileCardTypeId");
        Integer projectId1 = (Integer)operateMo.getEntity().get("projectId");
        Integer pipelineId = (Integer)operateMo.getEntity().get("pipelineId");
        Integer pipelineStationId = (Integer)operateMo.getEntity().get("pipelineStationId");
        if (Objects.isNull(pileCardTypeId)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[pileCardTypeId]");
        } else {
            if (validateModel.pileCardTypeIdValidate(pileCardTypeId)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pileCardTypeId]");
            }
        }
        if (Objects.isNull(projectId1)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[projectId]");
        } else {
            if (validateModel.projectIdValidate(projectId1)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[projectId],值不存在");
            }
        }
        if (Objects.nonNull(systemStakeNumber)) {
            final PileCard pileCard = validateModel.pileCardNumberValidate(systemStakeNumber, projectId1);
            if (Objects.nonNull(pileCard)){
                if(pileCard.getState().equals(0)){
                    return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[systemStakeNumber],值已存在");
                }else {
                    delete(pileCard.getId(),projectId1);
                }
            }
        }
        if (Objects.nonNull(pipelineId)) {
            if (validateModel.pipelineIdValidate(pipelineId,projectId1)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineId],值不存在");
            }
        }
        if (Objects.nonNull(pipelineStationId)){
            if (validateModel.pipelineStationIdValidate(pipelineStationId,projectId1)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineStationId],值不存在");
            }
        }
        if (Objects.nonNull(sceneImage)){
            if (validateModel.uploadImageValidate(FileTypeEnum.FILE_PILE_CARD_IMG.getValue(),sceneImage)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[sceneImage],文件不存在或文件上传类别错误");
            }
        }
        if (!pileCardService.insert(operateMo)){
            ro.setResultEnum(RoState.FAIL);
        }
        return ro;
    }

    @PatchMapping(value = "/modify")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<PileCard> modify(@RequestBody OperateMo operateMo, @RequestHeader("u-projectId") Integer projectId){
        Ro<PileCard> ro = new Ro<>();
        final ServiceRo serviceRo = operateMo.updateBuild(PileCard.class, projectId);
        if (!serviceRo.getResult()){
            return ro.setResultEnum(RoState.FAIL).setMessage(serviceRo.getMessage());
        }
        if (operateMo.getEntity().size()==0){
            return ro.setResultEnum(RoState.FAIL).setMessage("无操作参数传入,请传参后重试");
        }
        if (Objects.isNull(operateMo.get("id"))){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少[id]字段,请传参后重试");
        }
        String systemStakeNumber = (String) operateMo.getEntity().get("systemStakeNumber");
        String sceneImage = (String) operateMo.getEntity().get("sceneImage");
        Integer pileCardTypeId = (Integer) operateMo.getEntity().get("pileCardTypeId");
        Integer id = (Integer)operateMo.getEqMap().get("id");
        Integer projectId1 = (Integer)operateMo.getEqMap().get("project_id");
        Integer pipelineId = (Integer)operateMo.getEntity().get("pipelineId");
        Integer pipelineStationId = (Integer)operateMo.getEntity().get("pipelineStationId");
        if (Objects.nonNull(pileCardTypeId)){
            if (validateModel.pileCardTypeIdValidate(pileCardTypeId)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pileCardTypeId],值不存在");
            }
        }
        if (Objects.isNull(projectId1)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[projectId]");
        } else {
            if (validateModel.projectIdValidate(projectId1)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[projectId],值不存在");
            }
        }
        if (Objects.nonNull(systemStakeNumber)) {
            final PileCard pileCard = validateModel.pileCardNumberValidate(systemStakeNumber, projectId1);
            if (Objects.nonNull(pileCard)){
                if (!pileCard.getId().equals(id)){
                    if(pileCard.getState().equals(0)){
                        return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[systemStakeNumber],值已存在");
                    }else {
                        delete(pileCard.getId(),projectId1);
                    }
                }
            }
        }
        if (Objects.nonNull(pipelineId)){
            if (validateModel.pipelineIdValidate(pipelineId,projectId1)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineId],值不存在");
            }
        }
        if (Objects.nonNull(pipelineStationId)) {
            if (validateModel.pipelineStationIdValidate(pipelineStationId,projectId1)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineStationId]");
            }
        }
        if (Objects.nonNull(sceneImage)){
            if (validateModel.uploadImageValidate(FileTypeEnum.FILE_PILE_CARD_IMG.getValue(),sceneImage)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[sceneImage],文件不存在或文件上传类别错误");
            }
        }
        if (!pileCardService.update(operateMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("参数无匹配,修改失败");
        }
        return ro;
    }

    @DeleteMapping(value = "/delete/{id}")
    @Permission(value = 1,tags = Constants.API_SUPER)
    public Ro<PileCard> delete(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<PileCard> ro = new Ro<>();
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(PileCard.class,projectId);
        queryMo.getEqMap().remove("state");
        if (!pileCardService.delete(queryMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("无匹配ID,删除失败");
        }
        return ro;
    }

    @DeleteMapping(value = "/delete/logical/{id}")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<PileCard> logicallyDelete(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<PileCard> ro = new Ro<>();
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(PileCard.class,projectId);
        if (!pileCardService.logicallyDelete(queryMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("无匹配ID,删除失败");
        }
        return ro;
    }
}
